import uuidv4 from "../../node_modules/uuid/dist/esm-browser/v4.js";
import { getDataInfo } from "./initial.js";
import getNextTaskId from "./getNextTaskId.js";
import TaskManager from "./TaskManager.js";
import { MAX_CONCURRENT_TASKS } from "./constants.js";

const downloadStatus = document.querySelector("#DownloadStatus");
const downloadProgress = document.querySelector("#DownloadProgress");

// 待下载队列，初始化为mediaList的复制
let portObjs = [];
const manager = new TaskManager(MAX_CONCURRENT_TASKS);

export async function stopDownload() {
  console.error("停止portObjs", portObjs);

  // 清空队列
  manager.clearAllTasks();

  portObjs.forEach(({ portObj, taskid }) => {
    if (!portObj) {
      return;
    }
    const theUuid = uuidv4();
    portObj.postMessage({
      type: "hctpTransferStopTaskById",
      value: 0,
      theUuid,
      taskid,
    });
  });
}
// 处理下载的函数
export async function handleDownload() {
  const dataInfo = await getDataInfo();

  console.error("dataInfo.mediaList", dataInfo.mediaList.length);

  const newItems = [];

  for (const mediaItem of dataInfo.mediaList) {
    const newItem = createDbItem(mediaItem, dataInfo);
    newItems.push(newItem);
  }

  await new Promise((resolve, reject) => {
    const portObj = window.electronAPI.postMessage(
      "port-download",
      { type: "InsertDownloadMedia", newItems: newItems, date: Date.now() },
      (data) => {
        console.log("update database data", Date.now() - data.date);
        console.log("update database portObj", portObj);
        portObj.close();
        resolve(data);
      },
      (channel, event) => {
        console.error("channel, event", channel, event);
      }
    );
  });

  for (const newItem of newItems) {
    manager.add(uuidv4(), () =>
      downloadMediaItem({ ...newItem, token: dataInfo.deviceAuthData.token })
    );
  }
}

export function createDbItem(mediaItem, dataInfo) {
  const taskid = getNextTaskId();
  const portUuid = uuidv4();

  return {
    type: "DownloadMediaStart",
    uuid: portUuid,
    taskid: taskid,
    userid: dataInfo.userInfo.uid,
    status: 0,
    fileName: mediaItem.md5,
    fileSize: "",
    filePath: "",
    fileOwner: dataInfo.albumItem.owner,
    fileRemotePath: mediaItem.md5,
    fileMimeType: "",
    fileType: "",
    progress: 0,
    localDirectory: 'path.join(__dirname, "../../img/")',
    downloadDate: Date.now(),
    completedDate: Date.now(),
    groupDeviceId: dataInfo.deviceInfo.id,
    deviceId: dataInfo.deviceInfo.id,
    hostname: "",
    syKeyDid: dataInfo.systemKeyObj.did,
    syKeyInitString: dataInfo.systemKeyObj.initString,
    syKeyApiLicenses: dataInfo.systemKeyObj.apiLicenses,
    syKeyCrcKey: dataInfo.systemKeyObj.crcKey,
    playload: {
      albumid: dataInfo.albumItem.albumId,
      md5: mediaItem.md5,
    },
    code: 0,
  };
}
// 下载单个媒体项的函数
export async function downloadMediaItem(newItem) {
  return new Promise(async (resolve) => {
    downloadProgress.textContent = "0";
    downloadStatus.textContent = "准备下载";

    const portObj = window.electronAPI.postMessage(
      "port-download",
      newItem,
      (data) => {
        console.log("[data]", data);
        if (data.type === "progress") {
          downloadStatus.textContent = "下载中";
          downloadProgress.textContent = data.progress;
        }
        if (data.type === "ended") {
          console.log("messageEvent.data", data);

          portObjs = portObjs.filter((item) => item.taskid !== newItem.taskid);

          switch (data.code) {
            case 0:
              downloadStatus.textContent = "下载成功";
              break;
            case 3:
              downloadStatus.textContent = "下载暂停";
              break;
            default:
              downloadStatus.textContent = `下载失败,错误码${data.code},${data.msg}`;
              break;
          }
          portObj.close();
          resolve(); // 下载完成，解决Promise
        }
      },
      (channel, event) => {
        console.error("channel, event", channel, event);
      }
    );

    portObjs.push({ taskid: newItem.taskid, portObj });
  });
}
